using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
using System.Windows.Forms;
using GitProjectManager.Models;
using GitProjectManager.Services;

namespace GitProjectManager.Models;

public partial class MainForm : Form
{
    private readonly ProjectService _projectService = null!;
    private List<GitProject> _allProjects = new List<GitProject>();
    private bool _isProcessing = false;
    private string _iconLoadStatus = string.Empty;

    private ContextMenuStrip? _projectContextMenu;

    public MainForm(ProjectService projectService)
    {
        try
        {
            _projectService = projectService;
            InitializeComponent();
            InitializeDataGridView();
            InitializeContextMenu();
            LoadProjects();
        }
        catch (Exception ex)
        {
            MessageBox.Show($"初始化错误: {ex.Message}\n\n堆栈跟踪: {ex.StackTrace}", "应用程序错误", MessageBoxButtons.OK,
                MessageBoxIcon.Error);
        }
    }

    // 如果还需要无参构造函数（设计器需要）
    public MainForm() : this(new ProjectService(new ConfigService()))
    {
    }

    private void MainForm_Load(object sender, EventArgs e)
    {
        // 设置表格的滚动条
        dgvProjects.ScrollBars = ScrollBars.Both; // 启用水平和垂直滚动条

        // 添加DataError事件处理，避免显示默认错误对话框
        dgvProjects.DataError += new DataGridViewDataErrorEventHandler(dgvProjects_DataError);

        // 移除LoadProjects()调用，因为已在构造函数中调用，避免UpdateProgramComboBox()重复执行

        // 显示图标加载状态对话框
        if (!string.IsNullOrEmpty(_iconLoadStatus))
        {
            // 只在图标加载失败时显示消息
            if (!_iconLoadStatus.Contains("成功"))
            {
                MessageBox.Show(
                    _iconLoadStatus,
                    "图标加载状态",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Warning);
            }
        }

        // 确保事件处理器只添加一次
        dgvProjects.CellFormatting -= dgvProjects_CellFormatting;
        dgvProjects.CellFormatting += dgvProjects_CellFormatting;

        // 确保事件处理器只添加一次
        dgvProjects.Scroll -= dgvProjects_Scroll;
        dgvProjects.Scroll += dgvProjects_Scroll;

        // 注意：UpdateProgramComboBox()已在LoadProjects()中调用，无需在此处重复调用
    }

    private void dgvProjects_DataError(object sender, DataGridViewDataErrorEventArgs e)
    {
        try
        {
            // 处理DataGridViewComboBoxCell值无效的错误
            if (e.ColumnIndex >= 0 && e.RowIndex >= 0 &&
                dgvProjects.Columns[e.ColumnIndex] is DataGridViewComboBoxColumn)
            {
                // 检查是否是ProgramName列
                if (dgvProjects.Columns[e.ColumnIndex].Name == "ProgramName")
                {
                    // 确保行和单元格存在
                    if (e.RowIndex < dgvProjects.Rows.Count && dgvProjects.Rows[e.RowIndex] != null &&
                        dgvProjects.Rows[e.RowIndex].Cells[e.ColumnIndex] != null)
                    {
                        // 获取错误单元格
                        DataGridViewComboBoxCell cell =
                            (DataGridViewComboBoxCell)dgvProjects.Rows[e.RowIndex].Cells[e.ColumnIndex];

                        // 尝试更新下拉选项，确保有最新的程序列表
                        UpdateProgramComboBox();

                        // 获取当前单元格值
                        object currentValue = cell.Value;
                        string valueStr = currentValue?.ToString();

                        // 检查当前值是否在选项列表中
                        bool valueInList = false;
                        foreach (var item in cell.Items)
                        {
                            if (item != null && item.ToString() == valueStr)
                            {
                                valueInList = true;
                                break;
                            }
                        }

                        // 如果值不在列表中，则设置为默认值
                        if (!valueInList)
                        {
                            // 确保下拉选项已更新
                            if (cell.Items.Count > 0 && cell.Items.Contains("(使用默认IDE)"))
                            {
                                cell.Value = "(使用默认IDE)";
                            }
                            else
                            {
                                cell.Value = null;
                            }

                            // 记录错误到状态条，但不显示错误对话框
                            UpdateStatusStripMessage("已自动修正无效的程序选择");
                        }
                    }

                    // 取消显示错误对话框
                    e.Cancel = true;
                }
            }
        }
        catch (Exception ex)
        {
            // 捕获所有异常，确保不会显示默认错误对话框
            UpdateStatusStripMessage($"处理数据错误时发生异常: {ex.Message}");
            e.Cancel = true;
        }
    }

    public void UpdateProgramComboBox()
    {
        // 找到自定义程序列
        DataGridViewComboBoxColumn programColumn = dgvProjects.Columns["ProgramName"] as DataGridViewComboBoxColumn;
        if (programColumn != null)
        {
            // 清空现有选项
            programColumn.Items.Clear();
            programColumn.Items.Add("(使用默认IDE)");

            // 添加配置中的自定义程序
            if (_projectService != null)
            {
                foreach (var program in _projectService.GetExePrograms())
                {
                    programColumn.Items.Add(program);
                }
            }
        }

        // 同时更新程序列表显示
        // UpdateExeProgramsList(); // 不再需要，功能已移至单独的浮窗
    }

    // 不再需要，功能已移至单独的浮窗
    // private void UpdateExeProgramsList()
    // {
    //     // 更新程序列表显示
    //     lstExePrograms.Items.Clear();
    //     if (_projectService != null)
    //     {
    //         foreach (var program in _projectService.GetExePrograms())
    //         {
    //             lstExePrograms.Items.Add(program);
    //         }
    //     }
    // }

    // 不再需要，功能已移至单独的浮窗
    // private void UpdateExeProgramsList(ListBox listBox)
    // {
    //     // 更新指定列表框的程序列表显示
    //     listBox.Items.Clear();
    //     if (_projectService != null)
    //     {
    //         foreach (var program in _projectService.GetExePrograms())
    //         {
    //             listBox.Items.Add(program);
    //         }
    //     }
    // }

    private void btnAddExe_Click(object sender, EventArgs e)
    {
        try
        {
            // 创建一个简单的输入对话框
            Form inputForm = new Form();
            inputForm.Text = "添加自定义程序";
            inputForm.Width = 400;
            inputForm.Height = 200;
            inputForm.FormBorderStyle = FormBorderStyle.FixedDialog;
            inputForm.StartPosition = FormStartPosition.CenterParent;
            inputForm.MinimizeBox = false;
            inputForm.MaximizeBox = false;

            // 程序名称
            Label nameLabel = new Label();
            nameLabel.Text = "程序名称:";
            nameLabel.Location = new Point(20, 20);
            nameLabel.AutoSize = true;

            TextBox nameTextBox = new TextBox();
            nameTextBox.Location = new Point(120, 20);
            nameTextBox.Width = 250;

            // 程序路径
            Label pathLabel = new Label();
            pathLabel.Text = "程序路径:";
            pathLabel.Location = new Point(20, 50);
            pathLabel.AutoSize = true;

            TextBox pathTextBox = new TextBox();
            pathTextBox.Location = new Point(120, 50);
            pathTextBox.Width = 210;

            // 浏览按钮
            Button browseButton = new Button();
            browseButton.Text = "浏览...";
            browseButton.Location = new Point(335, 50);
            browseButton.Width = 35;
            browseButton.Click += (s, ev) =>
            {
                OpenFileDialog openFileDialog = new OpenFileDialog();
                openFileDialog.Filter = "可执行文件 (*.exe)|*.exe|所有文件 (*.*)|*.*";
                openFileDialog.Title = "选择可执行文件";
                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    pathTextBox.Text = openFileDialog.FileName;
                }
            };

            // 确认按钮
            Button okButton = new Button();
            okButton.Text = "确定";
            okButton.Location = new Point(200, 100);
            okButton.Width = 80;
            okButton.DialogResult = DialogResult.OK;

            // 取消按钮
            Button cancelButton = new Button();
            cancelButton.Text = "取消";
            cancelButton.Location = new Point(290, 100);
            cancelButton.Width = 80;
            cancelButton.DialogResult = DialogResult.Cancel;

            // 添加控件
            inputForm.Controls.Add(nameLabel);
            inputForm.Controls.Add(nameTextBox);
            inputForm.Controls.Add(pathLabel);
            inputForm.Controls.Add(pathTextBox);
            inputForm.Controls.Add(browseButton);
            inputForm.Controls.Add(okButton);
            inputForm.Controls.Add(cancelButton);

            inputForm.AcceptButton = okButton;
            inputForm.CancelButton = cancelButton;

            // 显示对话框
            if (inputForm.ShowDialog() == DialogResult.OK)
            {
                string programName = nameTextBox.Text.Trim();
                string programPath = pathTextBox.Text.Trim();

                if (!string.IsNullOrEmpty(programName) && !string.IsNullOrEmpty(programPath))
                {
                    if (File.Exists(programPath) || programPath.Contains(" "))
                    {
                        _projectService.AddExeProgram(programName, programPath);
                        UpdateProgramComboBox();
                        UpdateStatusStripMessage($"已添加程序: {programName}");
                    }
                    else
                    {
                        MessageBox.Show("指定的程序文件不存在！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else
                {
                    MessageBox.Show("请输入程序名称和路径！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
        catch (Exception ex)
        {
            ShowErrorMessage("添加程序失败", ex.Message);
        }
    }

    private void dgvProjects_CellValueChanged(object sender, DataGridViewCellEventArgs e)
    {
        // 此事件可能在绑定数据时触发，我们将主要逻辑放在CellEndEdit中
    }

    private void dgvProjects_CellEndEdit(object sender, DataGridViewCellEventArgs e)
    {
        try
        {
            // 确保是有效单元格且是ProgramName列
            if (e.RowIndex >= 0 && e.ColumnIndex >= 0 && dgvProjects.Columns[e.ColumnIndex].Name == "ProgramName")
            {
                GitProject project = dgvProjects.Rows[e.RowIndex].DataBoundItem as GitProject;
                if (project != null)
                {
                    object value = dgvProjects.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
                    project.ProgramName = value?.ToString() == "(使用默认IDE)" ? null : value?.ToString();
                    _projectService.UpdateProject(project);
                    UpdateStatusStripMessage($"已更新项目 '{project.Name}' 的自定义程序设置");
                }
            }
        }
        catch (Exception ex)
        {
            ShowErrorMessage("更新程序设置失败", ex.Message);
        }
    }


    // 打开自定义程序编辑浮窗
    private void btnToggleProgramEdit_Click(object sender, EventArgs e)
    {
        // 打开自定义程序编辑浮窗（模态）
        ProgramEditForm programEditForm = new ProgramEditForm(_projectService, this);
        programEditForm.ShowDialog(this); // 模态显示，必须关闭浮窗才能操作主窗口
    }


    private void InitializeContextMenu()
    {
        // 创建右键菜单
        _projectContextMenu = new ContextMenuStrip();

        // 添加菜单项
        ToolStripMenuItem menuOpenProject = new ToolStripMenuItem("打开项目");
        menuOpenProject.Click += MenuOpenProject_Click;
        _projectContextMenu.Items.Add(menuOpenProject);

        ToolStripMenuItem menuOpenFolder = new ToolStripMenuItem("打开项目文件夹");
        menuOpenFolder.Click += MenuOpenFolder_Click;
        _projectContextMenu.Items.Add(menuOpenFolder);

        _projectContextMenu.Items.Add(new ToolStripSeparator()); // 分隔线

        // Tortoise Git 相关功能
        ToolStripMenuItem menuTortoiseCommit = new ToolStripMenuItem("Tortoise Git 提交");
        menuTortoiseCommit.Click += MenuTortoiseCommit_Click;
        _projectContextMenu.Items.Add(menuTortoiseCommit);

        ToolStripMenuItem menuTortoiseRevert = new ToolStripMenuItem("Tortoise Git 回滚");
        menuTortoiseRevert.Click += MenuTortoiseRevert_Click;
        _projectContextMenu.Items.Add(menuTortoiseRevert);

        _projectContextMenu.Items.Add(new ToolStripSeparator()); // 分隔线

        // Git 操作
        ToolStripMenuItem menuGitFetch = new ToolStripMenuItem("Git Fetch");
        menuGitFetch.Click += MenuGitFetch_Click;
        _projectContextMenu.Items.Add(menuGitFetch);

        ToolStripMenuItem menuGitPush = new ToolStripMenuItem("Git Push");
        menuGitPush.Click += MenuGitPush_Click;
        _projectContextMenu.Items.Add(menuGitPush);

        ToolStripMenuItem menuGitPull = new ToolStripMenuItem("Git Pull");
        menuGitPull.Click += MenuGitPull_Click;
        _projectContextMenu.Items.Add(menuGitPull);

        ToolStripMenuItem menuGitStatus = new ToolStripMenuItem("查看Git状态");
        menuGitStatus.Click += MenuGitStatus_Click;
        _projectContextMenu.Items.Add(menuGitStatus);

        // 将右键菜单绑定到DataGridView
        dgvProjects.ContextMenuStrip = _projectContextMenu;
    }

    private void InitializeDataGridView()
    {
        // 配置DataGridView
        dgvProjects.AutoGenerateColumns = false;
        dgvProjects.CellValueChanged += new DataGridViewCellEventHandler(dgvProjects_CellValueChanged);
        dgvProjects.CellEndEdit += new DataGridViewCellEventHandler(dgvProjects_CellEndEdit);
        dgvProjects.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
        dgvProjects.MultiSelect = false;
        dgvProjects.ReadOnly = false; // 确保整个表格是可编辑的
        dgvProjects.AllowUserToResizeColumns = true; // 允许用户调整列宽
        dgvProjects.AllowUserToResizeRows = false;
        dgvProjects.ScrollBars = ScrollBars.Both; // 启用水平和垂直滚动条
        dgvProjects.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None; // 关闭自动列宽

        // 添加列
        dgvProjects.Columns.Add(new DataGridViewTextBoxColumn
        {
            Name = "Name",
            HeaderText = "项目名称",
            DataPropertyName = "Name",
            Width = 150, // 固定宽度
            Resizable = DataGridViewTriState.True
        });

        dgvProjects.Columns.Add(new DataGridViewTextBoxColumn
        {
            Name = "Path",
            HeaderText = "项目路径",
            DataPropertyName = "Path",
            Width = 400, // 增加宽度以更好地显示较长的Windows路径
            Resizable = DataGridViewTriState.True
        });

        dgvProjects.Columns.Add(new DataGridViewTextBoxColumn
        {
            Name = "CurrentBranch",
            HeaderText = "当前分支",
            DataPropertyName = "CurrentBranch",
            Width = 120, // 固定宽度
            Resizable = DataGridViewTriState.True
        });

        dgvProjects.Columns.Add(new DataGridViewTextBoxColumn
        {
            Name = "GitStatus",
            HeaderText = "Git状态",
            DataPropertyName = "GitStatus",
            Width = 100, // 状态列默认宽度较短，用户可以手动调整
            Resizable = DataGridViewTriState.True
        });

        // 自定义程序列
        DataGridViewComboBoxColumn programColumn = new DataGridViewComboBoxColumn
        {
            Name = "ProgramName",
            HeaderText = "自定义程序",
            DataPropertyName = "ProgramName",
            Width = 120,
            Resizable = DataGridViewTriState.True,
            ReadOnly = false // 确保列是可编辑的
        };
        programColumn.DefaultCellStyle.NullValue = "(使用默认IDE)";
        dgvProjects.Columns.Add(programColumn);

        dgvProjects.Columns.Add(new DataGridViewTextBoxColumn
        {
            Name = "LastCommitDate",
            HeaderText = "最后提交时间",
            DataPropertyName = "LastCommitDate",
            Width = 150, // 固定宽度
            Resizable = DataGridViewTriState.True
        });

        dgvProjects.Columns.Add(new DataGridViewTextBoxColumn
        {
            Name = "OpenCount",
            HeaderText = "打开次数",
            DataPropertyName = "OpenCount",
            Width = 100, // 固定宽度
            Resizable = DataGridViewTriState.True
        });
    }

    private void LoadProjects()
    {
        try
        {
            if (_projectService != null)
            {
                _allProjects = _projectService.GetAllProjects();
                dgvProjects.DataSource = _allProjects;
                UpdateStatusStripMessage($"已加载 {_allProjects.Count} 个项目");

                // 根据表格列宽动态调整窗口大小
                ResizeWindowBasedOnColumns();

                // 更新自定义程序下拉选项
                UpdateProgramComboBox();
            }
            else
            {
                UpdateStatusStripMessage("项目服务未初始化");
            }
        }
        catch (Exception ex)
        {
            ShowErrorMessage("加载项目失败", ex.Message);
        }
    }

    private void ResizeWindowBasedOnColumns()
    {
        try
        {
            // 计算所有列的总宽度
            int totalColumnWidth = dgvProjects.RowHeadersVisible ? dgvProjects.RowHeadersWidth : 0;
            foreach (DataGridViewColumn column in dgvProjects.Columns)
            {
                if (column != null && column.Visible)
                {
                    totalColumnWidth += column.Width;
                }
            }

            // 添加适当的边距和滚动条宽度
            int requiredWidth = totalColumnWidth + 40; // 边距

            // 确保宽度不小于最小宽度，也不超过屏幕宽度的80%
            int minWidth = 800;
            // 避免空引用，使用默认最大宽度
            int maxWidth = 1200; // 默认值
            if (Screen.PrimaryScreen != null)
            {
                maxWidth = (int)(Screen.PrimaryScreen.WorkingArea.Width * 0.8);
            }

            int newWidth = Math.Min(Math.Max(requiredWidth, minWidth), maxWidth);

            // 调整窗口大小，保持高度不变
            this.Width = newWidth;
        }
        catch (Exception ex)
        {
            UpdateStatusStripMessage($"调整窗口大小时出错: {ex.Message}");
        }
    }


    private void btnOpenConfig_Click(object sender, EventArgs e)
    {
        try
        {
            // 获取配置文件路径
            string configDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
                "GitProjectManager");
            string configFilePath = Path.Combine(configDirectory, "config.json");

            // 检查目录是否存在
            if (!Directory.Exists(configDirectory))
            {
                ShowErrorMessage("错误", "配置文件目录不存在");
                return;
            }

            // 如果配置文件存在，直接打开文件；否则打开目录
            if (File.Exists(configFilePath))
            {
                Process.Start(new ProcessStartInfo
                {
                    FileName = configFilePath,
                    UseShellExecute = true
                });
            }
            else
            {
                Process.Start(new ProcessStartInfo
                {
                    FileName = configDirectory,
                    UseShellExecute = true
                });
            }

            UpdateStatusStripMessage("已打开配置文件目录");
        }
        catch (Exception ex)
        {
            ShowErrorMessage("打开配置文件失败", ex.Message);
        }
    }

    private void btnScanProjects_Click(object sender, EventArgs e)
    {
        if (_isProcessing)
            return;

        if (_projectService == null)
        {
            ShowErrorMessage("错误", "项目服务未初始化");
            return;
        }

        try
        {
            _isProcessing = true;
            SetControlsEnabled(false);
            progressBar.Visible = true;
            progressBar.Style = ProgressBarStyle.Marquee;
            UpdateStatusStripMessage("正在扫描Git项目...");

            var progress = new Progress<string>(UpdateStatusMessage);

            // 在后台线程执行扫描操作
            var foundProjects = _projectService.AutoScanProjects(progress);

            // 更新UI
            LoadProjects();
            UpdateStatusStripMessage($"扫描完成，发现 {foundProjects.Count} 个新Git项目");
        }
        catch (Exception ex)
        {
            ShowErrorMessage("扫描失败", ex.Message);
        }
        finally
        {
            progressBar.Visible = false;
            _isProcessing = false;
            SetControlsEnabled(true);
        }
    }

    private async void btnRefreshStatus_Click(object sender, EventArgs e)
    {
        if (_isProcessing || _projectService == null)
            return;

        try
        {
            _isProcessing = true;
            SetControlsEnabled(false);
            progressBar.Visible = true;
            progressBar.Style = ProgressBarStyle.Marquee;
            UpdateStatusStripMessage("正在刷新项目状态...");

            var progress = new Progress<string>(UpdateStatusMessage);

            // 在后台线程执行刷新操作
            await Task.Run(() => _projectService.RefreshAllGitStatus(progress));

            // 更新UI
            LoadProjects();
            UpdateStatusStripMessage("项目状态刷新完成");
        }
        catch (Exception ex)
        {
            ShowErrorMessage("刷新失败", ex.Message);
        }
        finally
        {
            progressBar.Visible = false;
            _isProcessing = false;
            SetControlsEnabled(true);
        }
    }

    private void btnAddProject_Click(object sender, EventArgs e)
    {
        if (_projectService == null)
        {
            ShowErrorMessage("错误", "项目服务未初始化");
            return;
        }

        using (FolderBrowserDialog folderDialog = new FolderBrowserDialog())
        {
            folderDialog.Description = "选择Git项目文件夹";
            folderDialog.ShowNewFolderButton = false;

            if (folderDialog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    var projectPath = folderDialog.SelectedPath;

                    // 检查是否是Git仓库
                    if (_projectService.IsGitRepository(projectPath))
                    {
                        var project = new GitProject
                        {
                            Name = System.IO.Path.GetFileName(projectPath),
                            Path = projectPath
                        };

                        _projectService.AddProject(project);
                        LoadProjects();
                        UpdateStatusStripMessage($"成功添加项目: {project.Name}");
                    }
                    else
                    {
                        ShowErrorMessage("添加失败", "所选目录不是有效的Git仓库");
                    }
                }
                catch (Exception ex)
                {
                    ShowErrorMessage("添加失败", ex.Message);
                }
            }
        }
    }

    private void btnRemoveProject_Click(object sender, EventArgs e)
    {
        if (_projectService == null)
        {
            ShowErrorMessage("错误", "项目服务未初始化");
            return;
        }

        if (dgvProjects.SelectedRows.Count == 0)
        {
            ShowInfoMessage("提示", "请先选择要移除的项目");
            return;
        }

        var selectedProject = dgvProjects.SelectedRows[0].DataBoundItem as GitProject;

        if (selectedProject != null && MessageBox.Show(
                $"确定要移除项目 '{selectedProject.Name}' 吗？\n此操作不会删除实际文件。",
                "确认移除",
                MessageBoxButtons.YesNo,
                MessageBoxIcon.Question) == DialogResult.Yes)
        {
            try
            {
                _projectService.RemoveProject(selectedProject.Id);
                LoadProjects();
                UpdateStatusStripMessage($"已移除项目: {selectedProject.Name}");
            }
            catch (Exception ex)
            {
                ShowErrorMessage("移除失败", ex.Message);
            }
        }
    }

    private void btnOpenProject_Click(object sender, EventArgs e)
    {
        OpenSelectedProject();
    }

    private void dgvProjects_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
    {
        // 禁用双击打开项目功能，改为通过右键菜单操作
    }

    private void dgvProjects_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
    {
        // 设置单元格悬停效果
        if (e.RowIndex >= 0 && e.ColumnIndex >= 0)
        {
            DataGridViewRow row = dgvProjects.Rows[e.RowIndex];
            // 根据Git状态设置不同的行背景色
            if (e.ColumnIndex == 3) // 状态列
            {
                string status = e.Value?.ToString();
                if (status != null)
                {
                    if (status.Contains("未提交"))
                    {
                        e.CellStyle.ForeColor = Color.Red;
                        // 避免null引用
                        if (e.CellStyle.Font != null)
                        {
                            e.CellStyle.Font = new Font(e.CellStyle.Font, FontStyle.Bold);
                        }
                    }
                    else if (status.Contains("有变更"))
                    {
                        e.CellStyle.ForeColor = Color.Orange;
                        // 避免null引用
                        if (e.CellStyle.Font != null)
                        {
                            e.CellStyle.Font = new Font(e.CellStyle.Font, FontStyle.Italic);
                        }
                    }
                    else if (status.Contains("正常"))
                    {
                        e.CellStyle.ForeColor = Color.Green;
                    }
                }
            }
        }
    }

    private void dgvProjects_Scroll(object sender, ScrollEventArgs e)
    {
        // 滚动时可以添加额外的处理逻辑
        // 这里只是为了演示，实际上DataGridView默认已经支持滚轮功能
    }

    private void btnSearch_Click(object sender, EventArgs e)
    {
        SearchProjects(txtSearch.Text.Trim());
    }

    private void txtSearch_KeyPress(object sender, KeyPressEventArgs e)
    {
        // 按Enter键搜索
        if (e.KeyChar == (char)Keys.Enter)
        {
            e.Handled = true;
            SearchProjects(txtSearch.Text.Trim());
        }
    }

    private void SearchProjects(string keyword)
    {
        try
        {
            if (string.IsNullOrEmpty(keyword))
            {
                dgvProjects.DataSource = _allProjects;
                UpdateStatusStripMessage($"显示所有项目: {_allProjects.Count} 个");
            }
            else
            {
                var searchResults = _projectService.SearchProjects(keyword);
                dgvProjects.DataSource = searchResults;
                UpdateStatusStripMessage($"搜索结果: {searchResults.Count} 个项目");
            }
        }
        catch (Exception ex)
        {
            ShowErrorMessage("搜索失败", ex.Message);
        }
    }

    private void SearchProjects()
    {
        try
        {
            var keyword = txtSearch.Text.Trim();
            var searchResults = _projectService.SearchProjects(keyword);
            dgvProjects.DataSource = searchResults;
            UpdateStatusStripMessage($"搜索结果: {searchResults.Count} 个项目");
        }
        catch (Exception ex)
        {
            ShowErrorMessage("搜索失败", ex.Message);
        }
    }

    private void OpenSelectedProject()
    {
        if (dgvProjects.SelectedRows.Count == 0)
        {
            ShowInfoMessage("提示", "请先选择要打开的项目");
            return;
        }

        var selectedProject = dgvProjects.SelectedRows[0].DataBoundItem as GitProject;

        if (selectedProject == null)
        {
            ShowInfoMessage("提示", "无法获取选中的项目信息");
            return;
        }

        try
        {
            if (_projectService != null)
            {
                _projectService.OpenProject(selectedProject);
                UpdateStatusStripMessage($"正在打开项目: {selectedProject.Name}");
            }
            else
            {
                ShowErrorMessage("错误", "项目服务未初始化");
            }
        }
        catch (Exception ex)
        {
            ShowErrorMessage("打开失败", ex.Message);
        }
    }

    private void UpdateStatusMessage(string message)
    {
        if (InvokeRequired)
        {
            Invoke(new Action<string>(UpdateStatusMessage), message);
            return;
        }

        lblStatus.Text = message;
    }

    // UpdateStatusStripMessage方法在文件末尾有定义

    #region 右键菜单事件处理

    private void MenuOpenProject_Click(object sender, EventArgs e)
    {
        // 确保有选中的项目
        if (dgvProjects.SelectedRows.Count > 0 && _projectService != null)
        {
            OpenSelectedProject();
        }
    }

    private void MenuOpenFolder_Click(object sender, EventArgs e)
    {
        try
        {
            if (dgvProjects.SelectedRows.Count > 0)
            {
                GitProject project = (GitProject)dgvProjects.SelectedRows[0].DataBoundItem;
                if (Directory.Exists(project.Path))
                {
                    System.Diagnostics.Process.Start("explorer.exe", project.Path);
                    UpdateStatusStripMessage($"已打开文件夹: {project.Path}");
                }
            }
        }
        catch (Exception ex)
        {
            ShowErrorMessage("打开文件夹失败", ex.Message);
        }
    }

    private void MenuTortoiseCommit_Click(object sender, EventArgs e)
    {
        try
        {
            if (dgvProjects.SelectedRows.Count > 0)
            {
                GitProject project = (GitProject)dgvProjects.SelectedRows[0].DataBoundItem;
                if (Directory.Exists(project.Path))
                {
                    // 使用TortoiseGit提交
                    System.Diagnostics.Process.Start("TortoiseGitProc.exe", $"/command:commit /path:{project.Path}");
                    UpdateStatusStripMessage($"已打开TortoiseGit提交: {project.Name}");
                }
            }
        }
        catch (Exception ex)
        {
            ShowErrorMessage("启动TortoiseGit提交失败", ex.Message);
        }
    }

    private void MenuTortoiseRevert_Click(object sender, EventArgs e)
    {
        try
        {
            if (dgvProjects.SelectedRows.Count > 0)
            {
                GitProject project = (GitProject)dgvProjects.SelectedRows[0].DataBoundItem;
                if (Directory.Exists(project.Path))
                {
                    // 使用TortoiseGit回滚
                    System.Diagnostics.Process.Start("TortoiseGitProc.exe", $"/command:revert /path:{project.Path}");
                    UpdateStatusStripMessage($"已打开TortoiseGit回滚: {project.Name}");
                }
            }
        }
        catch (Exception ex)
        {
            ShowErrorMessage("启动TortoiseGit回滚失败", ex.Message);
        }
    }

    private void MenuGitFetch_Click(object sender, EventArgs e)
    {
        try
        {
            if (dgvProjects.SelectedRows.Count > 0)
            {
                GitProject project = (GitProject)dgvProjects.SelectedRows[0].DataBoundItem;
                // 使用TortoiseGit执行Fetch
                System.Diagnostics.Process.Start("TortoiseGitProc.exe", $"/command:fetch /path:{project.Path}");
                UpdateStatusStripMessage($"已打开TortoiseGit Fetch: {project.Name}");
            }
        }
        catch (Exception ex)
        {
            ShowErrorMessage("启动TortoiseGit Fetch失败", ex.Message);
        }
    }

    private void MenuGitPush_Click(object sender, EventArgs e)
    {
        try
        {
            if (dgvProjects.SelectedRows.Count > 0)
            {
                GitProject project = (GitProject)dgvProjects.SelectedRows[0].DataBoundItem;
                // 使用TortoiseGit执行Push
                System.Diagnostics.Process.Start("TortoiseGitProc.exe", $"/command:push /path:{project.Path}");
                UpdateStatusStripMessage($"已打开TortoiseGit Push: {project.Name}");
            }
        }
        catch (Exception ex)
        {
            ShowErrorMessage("启动TortoiseGit Push失败", ex.Message);
        }
    }

    private void MenuGitPull_Click(object sender, EventArgs e)
    {
        try
        {
            if (dgvProjects.SelectedRows.Count > 0)
            {
                GitProject project = (GitProject)dgvProjects.SelectedRows[0].DataBoundItem;
                // 使用TortoiseGit执行Pull
                System.Diagnostics.Process.Start("TortoiseGitProc.exe", $"/command:pull /path:{project.Path}");
                UpdateStatusStripMessage($"已打开TortoiseGit Pull: {project.Name}");
            }
        }
        catch (Exception ex)
        {
            ShowErrorMessage("启动TortoiseGit Pull失败", ex.Message);
        }
    }

    private void MenuGitStatus_Click(object sender, EventArgs e)
    {
        try
        {
            if (dgvProjects.SelectedRows.Count > 0)
            {
                GitProject project = (GitProject)dgvProjects.SelectedRows[0].DataBoundItem;

                // 使用cmd窗口显示Git状态
                System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo
                {
                    FileName = "cmd.exe",
                    Arguments = $"/c git status && pause",
                    WorkingDirectory = project.Path,
                    UseShellExecute = true,
                    CreateNoWindow = false
                });
            }
        }
        catch (Exception ex)
        {
            ShowErrorMessage("获取Git状态失败", ex.Message);
        }
    }

    #endregion

    private void UpdateStatusStripMessage(string message)
    {
        if (InvokeRequired)
        {
            Invoke(new Action<string>(UpdateStatusStripMessage), message);
            return;
        }

        toolStripStatusLabel.Text = message;
    }

    private void SetControlsEnabled(bool enabled)
    {
        if (InvokeRequired)
        {
            Invoke(new Action<bool>(SetControlsEnabled), enabled);
            return;
        }

        btnScanProjects.Enabled = enabled;
        btnRefreshStatus.Enabled = enabled;
        btnAddProject.Enabled = enabled;
        btnRemoveProject.Enabled = enabled;
        btnOpenProject.Enabled = enabled;
        btnSearch.Enabled = enabled;
        txtSearch.Enabled = enabled;
        dgvProjects.Enabled = enabled;
    }

    private void ShowErrorMessage(string title, string message)
    {
        if (InvokeRequired)
        {
            Invoke(new Action<string, string>(ShowErrorMessage), title, message);
            return;
        }

        MessageBox.Show(message, title, MessageBoxButtons.OK, MessageBoxIcon.Error);
        UpdateStatusStripMessage($"错误: {message}");
    }

    private void ShowInfoMessage(string title, string message)
    {
        if (InvokeRequired)
        {
            Invoke(new Action<string, string>(ShowInfoMessage), title, message);
            return;
        }

        MessageBox.Show(message, title, MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
}